<template>
    <div class="camera-list">
        <search-table
            ref="selectTable"
            :columns="columns"
            :data="cameraList"
            :total="total"
            :size.sync="pageSize"
            :page.sync="pageIndex"
            showSelectTag
            selectKey="cameraId"
            selectName="cameraName"
            :selection.sync="selectCameras"
            @queryFun="getCameraList">
            <!-- <template slot="checkbox-group">
                <Checkbox v-model="selectAll" :disabled="cameraList.length === 0 || disabledAllBtn" @on-change="selectAllChange">全选</Checkbox>
            </template> -->
            <template slot="button-group">
                <Button
                    type="primary"
                    ghost
                    @click="showModal = true; isAdd = true; modalTitle = '添加摄像头';"
                    icon="md-add">添加摄像头</Button>
                <Poptip 
                    confirm 
                    title="你确定要删除选中的摄像头吗？"
                    transfer
                    @on-ok="batchesDelete">
                    <Button
                        type="error"
                        ghost
                        :disabled="selectCameras.length === 0"
                        icon="ios-trash-outline">批量删除</Button>
                </Poptip>
            </template>
            <template slot="input-group">
                <Input v-model.trim="cameraName" placeholder="请输入摄像头名称" />
            </template>
        </search-table>
        <Modal
            v-model="showModal"
            width="800"
            :title="modalTitle">
            <Form ref="form" :model="formData" :rules="rules" :label-width="70">
                <FormItem label="名称" prop="cameraName">
                    <Input
                        v-model="formData.cameraName"
                        placeholder="请输入摄像头名称"></Input>
                </FormItem>
                <FormItem label="地址" prop="accessPath">
                    <Input
                        v-model="formData.accessPath"
                        type="textarea" 
                        :rows="4"
                        placeholder="请输入访问地址"></Input>
                </FormItem>
                <FormItem label="描述" prop="description">
                    <Input
                        v-model="formData.description"
                        type="textarea" 
                        :rows="4"
                        placeholder="请输入描述"></Input>
                </FormItem>
            </Form>
            <div slot="footer" class="footer">
                <Button type="text" size="large" @click="showModal = false">取消</Button>
                <Button type="primary" size="large" @click="confirm" :loading="loading">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import SearchTable from '@/components/SearchTable/SearchTable'
    import { getCameraList, addCamera, deleteCamera, updateCamera, pushCameraData } from '@/api/cameras'

    export default {
        name: 'CameraList',
        components: {
            SearchTable
        },
        props: {
            disabledAllBtn: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                selectAll: false,
                loading: false,
                modalTitle: '',
                formData: {
                    cameraName: '',
                    accessPath: '',
                    description: ''
                },
                showModal: false, // 展示添加摄像头的modal
                rules: {
                    cameraName: [
                        {required: true, message: '名称不能为空', trigger: 'change' }
                    ],
                    accessPath: [
                        {required: true, message: '访问地址不能为空', trigger: 'change' }
                    ],
                },
                columns: [
                    {
                        type:'selection',
                        width:60,
                    },
                    {
                        placement: 'top-left',
                        title: '摄像头名称',
                        key: 'cameraName',
                        align: 'center',
                        tooltip: true,
                        width: 230
                    },
                    {
                        title: '摄像头访问地址',
                        width: 300,
                        key: 'accessPath',
                        tooltip: true
                    },
                    {
                        title: '创建者',
                        width: 120,
                        key: 'creatorName',
                        tooltip: true
                    },
                    {
                        title: '创建时间',
                        width: 140,
                        key: 'createTime'
                    },
                    {
                        title: '设备状态',
                        width: 140,
                        key: 'status',
                        render:(h,params) => {
                            let status = params.row.status
                            return h('Tag', {
                                props:{
                                    color: status === 0 ? 'var(--status-no)' : 'var(--status-yes)'
                                }, 
                            }, status === 0 ? '离线' : '在线')
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 300,
                        opList: [
                            {
                                txt: '启动',
                                tooltip: true,
                                title: '你确定要启动吗？',
                                disabled: (data) => {
                                    return data.status !== 0 || this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.pushCameraData(data.cameraId, 'start');
                                }
                            },
                            {
                                txt: '停止',
                                tooltip: true,
                                type: 'delete',
                                title: '你确定要停止吗？',
                                disabled: (data) => {
                                    return data.status === 0 || this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.pushCameraData(data.cameraId, 'stop');
                                }
                            },
                            {
                                txt: '修改',
                                disabled: (data) => {
                                    return this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.showModal = true;
                                    this.isAdd = false;
                                    this.modalTitle = '编辑摄像头';
                                    this.formData = Object.assign({}, data);
                                }
                            },
                            {
                                txt: '删除',
                                type: 'delete',
                                tooltip: true,
                                title: '你确定要删除吗？',
                                disabled: (data) => {
                                    return this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.deleteCamera([data.cameraId]);
                                }
                            }
                        ]
                    },
                    {
                        title:'操作',
                        placement:'top-right',
                        key:'action1',
                        show:false,
                        render:(h,params) => {
                            return h('div',[
                                h('Poptip', {
									props: {
										confirm: true,
										type: 'error',
										size: 'large',
										title: '你确定要启动吗？',
										transfer:true
									},
									on: {
										'on-ok': () => {
                                            this.pushCameraData(params.row.cameraId, 'start')
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'primary',
											size: 'small',
                                            disabled: params.row.status !== 0 || this.disabledAllBtn
										},
										style: {
											marginRight: '5px'
										},
									}, '启动')
								]),
                                h('Poptip', {
									props: {
										confirm: true,
										type: 'error',
										size: 'large',
										title: '你确定要停止吗？',
										transfer:true
									},
									on: {
										'on-ok': () => {
                                            this.pushCameraData(params.row.cameraId, 'stop')
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'primary',
											size: 'small',
                                            disabled: params.row.status === 0 || this.disabledAllBtn
										},
										style: {
											marginRight: '5px'
										},
									}, '停止')
								]),
                                h('Button',{
                                    props:{
                                        type:'primary',
                                        size:'small',
                                        disabled:this.disabledAllBtn
                                    },
                                    style:{
                                        marginRight:'5px'
                                    },
                                    on:{
                                        click:()=>{
                                            this.showModal = true
                                            this.isAdd = false
                                            this.modalTitle = '修改摄像头'
                                            this.formData = Object.assign({}, params.row)
                                        }
                                    }
                                },"修改"),
                                h('Poptip', {
									props: {
										confirm: true,
										'ok-text': "确定",
										'cancel-text': "取消",
										type: 'error',
										size: 'large',
										title: '你确定要删除吗?',
										transfer:true
									},
									on: {
										'on-ok': () => {
											this.deleteCamera([params.row.cameraId])
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'error',
											size: 'small',
                                            disabled:this.disabledAllBtn
										},
										style: {
											marginRight: '5px'
										},
									}, '删除')
								])
                            ])
                        }
                    }
                ],
                total: 0, // 总数据量
                pageSize: 10, // 分页大小
                pageIndex: 1, // 当前页
                cameraName: '', // 搜索条件，摄像头名称
                cameraList: [], // 摄像头列表,
                selectCameras:[]
            }
        },
        mounted() {
            // this.getPageSize()
            // window.addEventListener('resize', this.getPageSize)
            this.getCameraList();
        },
        computed: {
            // checkedCameraIds() {
            //     let cameraIds = []
            //     this.cameraList.forEach(item => {
            //         if (item.checked) {
            //             cameraIds.push(item.cameraId)
            //         }
            //     })
            //     return cameraIds
            // }
        },
        methods: {
            // 动态获取pagesize的合适值
            // getPageSize() {
            //     clearTimeout(this.pageSizeTimer)
            //     this.pageSizeTimer = setTimeout(() => {
            //         let height = this.$refs.cardlist.$el.offsetHeight
            //         this.pageSize = Math.floor(height / 96) || 1
            //     }, 200)
            // },
            // 推送摄像头的状态
            pushCameraData(cameraId, operation) {
                pushCameraData(cameraId, operation).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.$Message.info(`${operation === 'start' ? '启动' : '停止'}摄像头成功`)
                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            this.getCameraList()
                        }, 2000)
                    }
                })
            },
            // 获取摄像头列表
            getCameraList(pageNow = this.pageIndex) {
                this.pageIndex = pageNow
                getCameraList({
                   cameraName: this.cameraName, 
                   pageIndex: this.pageIndex, 
                   pageSize: this.pageSize
                }).then(({ code, data, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.total = data.count || 0
                        this.cameraList = data.list || []
                        this.selectAll = false // 每次刷新数据后，重置全选
                    }
                }).catch(() => {
                    this.$Message.error('查询摄像头异常')
                })
            },
            // 确认添加/修改操作
            confirm() {
                this.$refs.form.validate(type => {
                    if (type) {
                        if (this.isAdd) {
                            this.addCamera()
                        } else {
                            this.updateCamera()
                        }
                    }
                })
            },
            // 添加摄像头
            addCamera() {
                this.loading = true
                addCamera(this.formData).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.$Message.info('添加摄像头成功')
                        this.cameraName = ''
                        this.getCameraList(1)
                        this.showModal = false
                    }
                }).catch(() => {
                    this.$Message.error('添加摄像头异常')
                }).finally(() => {
                    this.loading = false
                })
            },
            // 修改摄像头
            updateCamera() {
                this.loading = true
                updateCamera(this.formData.cameraId, this.formData).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.$Message.info('修改摄像头成功')
                        this.getCameraList()
                        this.showModal = false
                    }
                }).catch(() => {
                    this.$Message.error('修改摄像头异常')
                }).finally(() => {
                    this.loading = false
                })
            },
            // 删除摄像头
            deleteCamera(cameraIds) {
                deleteCamera(cameraIds).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        // 删除后展示当前页，当前页没有数据展示前一页
                        this.pageIndex = (this.cameraList.length == 1 && this.pageIndex > 1) 
                            ? this.pageIndex - 1 
                            : this.pageIndex
                        this.getCameraList()
                        this.$refs.selectTable.delSelectItem(cameraIds[0]);
                        this.$Message.info('删除摄像头成功')
                    }
                }).catch(() => {
                    this.$Message.error('删除摄像头异常')
                })
            },
            // 批量删除摄像头
            batchesDelete() {
                let cameraIds = this.selectCameras.map(item => item.cameraId)
                deleteCamera(cameraIds).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        // 删除后展示当前页，当前页没有数据展示前一页
                        this.pageIndex = (this.cameraList.length == cameraIds.length && this.pageIndex > 1) 
                            ? this.pageIndex - 1 
                            : this.pageIndex
                        this.getCameraList()
                        this.$Message.info('批量删除摄像头成功')
                        this.selectCameras = [];
                    }
                }).catch(() => {
                    this.$Message.error('批量删除摄像头异常')
                })
            },
            // 修改全选的状态
            changeSelectAll(state, item) {
                for (let i = 0, length = this.cameraList.length; i < length; i++) {
                    if (item.cameraId === this.cameraList[i].cameraId) {
                        this.$set(this.cameraList[i], 'checked', state)
                    }
                    if (!this.cameraList[i].checked) {
                        this.selectAll = false
                        return
                    }
                }
                this.selectAll = true
            },
            // 点击全选
            // selectAllChange(val) {
            //     this.cameraList.forEach(item => {
            //         this.$set(item, 'checked', val)
            //     })
            // }
        },
        watch: {
            showModal(val) { // 模态框隐藏时，清空数据和验证信息
                if (!val) {
                    this.$refs.form.resetFields()
                }
            },
            cameraName() { // 摄像头名称改变时，重新获取首页数据
                clearTimeout(this.timer)
                this.timer = setTimeout(() => {
                    this.getCameraList(1)
                }, 200)
            },
            // pageSize() {
            //     this.getCameraList(1)
            // }
        },
        beforeDestroy(){
            // window.removeEventListener('resize', this.getPageSize)
            clearTimeout(this.timer)
            clearTimeout(this.pageSizeTimer)
        }
    }
</script>

<style scoped>
    .camera-list {
        height: calc(100% - 16px);
    }
    .camera-list .search-table {
        height: 100%;
    }
    .camera-list /deep/ #cardList {
        height: calc(100vh - 146px);
        max-height: unset;
    }
    .camera-list /deep/ #cardList .defGraphWrap {
        height: 100%;
    }
</style>